package com.apes.fa.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fa.model.FaAssetsTransferOut;
import com.apes.fa.model.FaAssetsTransferOutItem;
import com.apes.fa.model.FaCard;
import com.apes.fa.respository.FaAssetsTransferOutRepository;
import com.apes.fa.respository.FaCardRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.jpa.spec.model.Group;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.rbac.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fa.service
 * @ClassName: FaAssetsTransferOutService
 * @Author: PengZiFeng
 * @Description: 资产转出(账套内)
 * @CreateTime: 2021-09-01 16:07
 * @Version: 1.0
 */

@Service("faAssetsTransferOutService")
public class FaAssetsTransferOutService extends DomainService {

    @Autowired
    private FaAssetsTransferOutRepository faAssetsTransferOutRepository;
    @Autowired
    private FaCardRepository faCardRepository;
    @Autowired
    private PartyRoleRepository partyRoleRepository;
    @Autowired
    private DeptRepository deptRepository;

    /**
     * 保存
     */
    public FaAssetsTransferOut save(SimpleRequest request){
        /*  JSONArray items = request.getJO().getJSONArray("faAssetsTransferOutItems");
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = items.getJSONObject(i);
            if (item.getString("inquirySelectState").equals("")) return null;
        }*/
        FaAssetsTransferOut faAssetsTransferOut = request.getO(FaAssetsTransferOut.class);
        faAssetsTransferOut.setState("create");
        List<FaAssetsTransferOutItem> faAssetsTransferOutItems = faAssetsTransferOut.getFaAssetsTransferOutItems();


        if (faAssetsTransferOutItems.size() !=0 && !faAssetsTransferOutItems.isEmpty()){
            List<String> collect = faAssetsTransferOutItems.stream().map(faAssetsTransferOutItem -> faAssetsTransferOutItem.getFaCard().getId()).collect(Collectors.toList());
            collect.stream().distinct().collect(Collectors.toList());
            if (collect.stream().distinct().count() != faAssetsTransferOutItems.size()){
                throw new RuntimeException("存在重复卡片请检查！！！");
            }
        }
//        faAssetsTransferOutItems.forEach(item ->{
//            List<FaAssetsTransferOut> useCard = faAssetsTransferOutRepository.findUseCard(item.getFaCard().getId());
//            if(useCard.size() != 0){
//                useCard.forEach(card ->{
//                    card.getFaAssetsTransferOutItems().forEach( outItem ->{
//                        throw new RuntimeException("该卡片id: "+outItem.getFaCard().getId()+" 已存在资产转出（账套内）单号:"+ card.getId());
//                    } );
//                });
//
//            }
//        });

        return faAssetsTransferOutRepository.saveAndFlush(faAssetsTransferOut);
    }

    /**
     * 删除
     */
    public String delete(SimpleRequest request){

        FaAssetsTransferOut faAssetsTransferOut = request.getO(FaAssetsTransferOut.class);
        faAssetsTransferOutRepository.delete(faAssetsTransferOut);
        return "删除成功！";

    }

    /**
     * 审核
     */
    public FaAssetsTransferOut approve(SimpleRequest request){

        FaAssetsTransferOut faAssetsTransferOut = request.getO(FaAssetsTransferOut.class);
        faAssetsTransferOut.setState("approve");
        faAssetsTransferOut.setApproveDate(new Date());
        faAssetsTransferOut.setApproveUid(this.getPerson(request));
        return faAssetsTransferOutRepository.saveAndFlush(faAssetsTransferOut);

    }

    /**
     * 发货
     */
    public FaAssetsTransferOut sendGoods(SimpleRequest request){

        FaAssetsTransferOut faAssetsTransferOut = request.getO(FaAssetsTransferOut.class);
        List<FaAssetsTransferOutItem> faAssetsTransferOutItems = faAssetsTransferOut.getFaAssetsTransferOutItems();
        JSONArray items = request.getJO().getJSONArray("faAssetsTransferOutItems");
        for (FaAssetsTransferOutItem faAssetsTransferOutItem : faAssetsTransferOutItems) {
            for (int i = 0; i < items.size(); i++) {
                JSONObject item = items.getJSONObject(i);
                if (Objects.isNull(item.get("selected"))) throw new RuntimeException("请最少选择一张卡片进行本次发货");
                if(item.get("selected").toString() == "true" ? true : false){
                    if(item.get("id").equals(faAssetsTransferOutItem.getId())){
                        if(!faAssetsTransferOutItem.isSendMark()){
                            faAssetsTransferOutItem.setSendDate(new Date());
                            faAssetsTransferOutItem.setConsigner(this.getPerson(request));
                            faAssetsTransferOutItem.setInquirySelectState(true);
                            faAssetsTransferOutItem.setSendMark(true);
                        }else {
                            throw new RuntimeException("请确定本次发货的卡片");
                        }
                    }
                }else{
                    if(item.get("id").equals(faAssetsTransferOutItem.getId())){
                        if(!faAssetsTransferOutItem.isInquirySelectState()) {
                            faAssetsTransferOutItem.setInquirySelectState(false);
                            faAssetsTransferOutItem.setSendMark(false);
                        }
                    }
                }
            }
        }
        faAssetsTransferOut.setFaAssetsTransferOutItems(faAssetsTransferOutItems);
        FaAssetsTransferOut faAssetsTransferOutNew = faAssetsTransferOutRepository.saveAndFlush(faAssetsTransferOut);
        return judgeSend(faAssetsTransferOutNew);

    }

    private FaAssetsTransferOut judgeSend(FaAssetsTransferOut faAssetsTransferOut){

        boolean flag = true;
        List<FaAssetsTransferOutItem> faAssetsTransferOutItems = faAssetsTransferOut.getFaAssetsTransferOutItems();
        for (FaAssetsTransferOutItem faAssetsTransferOutItem : faAssetsTransferOutItems) {//判断，如果有一个标识是否的话，就是部分发货
            if(!faAssetsTransferOutItem.isSendMark()){
                flag = false;
            }
        }
        if(flag){
            faAssetsTransferOut.setSendGoodsState("全部发货");
            faAssetsTransferOut.setState("send");
        }else{
            faAssetsTransferOut.setSendGoodsState("部分发货");
            faAssetsTransferOut.setState("partSend");
        }
        return faAssetsTransferOut;

    }

    /**
     * 收货
     */
    public FaAssetsTransferOut receiptGoods(SimpleRequest request){

        FaAssetsTransferOut faAssetsTransferOut = request.getO(FaAssetsTransferOut.class);
        List<FaAssetsTransferOutItem> faAssetsTransferOutItems = faAssetsTransferOut.getFaAssetsTransferOutItems();
        JSONArray items = request.getJO().getJSONArray("faAssetsTransferOutItems");
        for (FaAssetsTransferOutItem faAssetsTransferOutItem : faAssetsTransferOutItems) {
            for (int i = 0; i < items.size(); i++) {
                JSONObject item = items.getJSONObject(i);
                if (Objects.isNull(item.get("selected"))) throw new RuntimeException("请最少选择一张卡片进行本次收货");
                if(item.get("selected").toString() == "true" ? true : false){
                    if(item.get("id").equals(faAssetsTransferOutItem.getId())){
//                        if(faAssetsTransferOutItem.isInquirySelectState()){
                        if(faAssetsTransferOutItem.isSendMark()){
//                            faAssetsTransferOutItem.setInquirySelectState(true);
                            FaCard faCard = faCardRepository.findById(faAssetsTransferOutItem.getFaCard().getId()).get();
                            faCard.setDept(faAssetsTransferOut.getReceiptDept());
                            faCard.setUseDept(faAssetsTransferOut.getReceiptDept());
                            faCard.setResponsiblePerson(faAssetsTransferOutItem.getPrincipal());
                            faCard.setCustodian(faAssetsTransferOutItem.getCustodian());
                            faAssetsTransferOutItem.setAcceptanceDate(new Date());
                            faAssetsTransferOutItem.setAcceptancer(this.getPerson(request));
                            faAssetsTransferOutItem.setReceiptMark(true);
                        }else{
                            throw new RuntimeException("请确定本次收货的卡片");
                        }
                    }
                }else{
                    if(item.get("id").equals(faAssetsTransferOutItem.getId())){
                        if(!faAssetsTransferOutItem.isSendMark()) {
//                            faAssetsTransferOutItem.setInquirySelectState(false);
                            faAssetsTransferOutItem.setReceiptMark(false);
                        }
                    }
                }
            }
        }
        faAssetsTransferOut.setFaAssetsTransferOutItems(faAssetsTransferOutItems);
        FaAssetsTransferOut faAssetsTransferOutNew = faAssetsTransferOutRepository.saveAndFlush(faAssetsTransferOut);
        return judgeReceipt(faAssetsTransferOutNew);
    }

    private FaAssetsTransferOut judgeReceipt(FaAssetsTransferOut faAssetsTransferOut){

        boolean receiptFlag = true;
        List<FaAssetsTransferOutItem> faAssetsTransferOutItems = faAssetsTransferOut.getFaAssetsTransferOutItems();
        for (FaAssetsTransferOutItem faAssetsTransferOutItem : faAssetsTransferOutItems) {//判断，如果有一个标识是否的话，就是部分收货
            if(!faAssetsTransferOutItem.isReceiptMark()){
                receiptFlag = false;
            }
        }
        if(receiptFlag){
            faAssetsTransferOut.setReceiptGoodsState("全部收货");
            faAssetsTransferOut.setState("receipt");
        }else {
            faAssetsTransferOut.setReceiptGoodsState("部分收货");
            faAssetsTransferOut.setState("partReceipt");
        }

        return faAssetsTransferOut;

    }

    /**
     * 查询所有 （包含发货和收货部门权限）
     * @return
     */
    public Page<FaAssetsTransferOut> findAll(SimpleRequest request){
        Group group = JpaDsl.getGroup(request);
        group.addGroup(addDeptAuth(request));
        return SpringManager.getBean(FaAssetsTransferOutRepository.class).findAll(group.build(false), JpaDsl.getPageable(request));
    }

    /**
     * 增加部门查询权限
     */
    public Group addDeptAuth(SimpleRequest request){
        List<String> orgIds = SpringManager.getBean(PostService.class).findLocalPermitItems(request.getPostId(), "pp_search", "pt_dept");
        Group group = new Group();
        if (!orgIds.isEmpty() && orgIds.size() != 0){
            group.setOperator("or");
            group.addFilters(JpaDsl.toFilter(
                    "sendDept.id", "IN", orgIds,
                    "receiptDept.id", "IN", orgIds
            ));
        }
        return group;
    }

    public JSONObject beImportFaAssets(SimpleRequest request) {
        JSONObject importData = request.get("importData");//Excel信息
        //定义变量
        JSONArray field = request.get("data");
        JSONObject exclObject = new JSONObject();                  //返回值
        JSONArray exclArr = new JSONArray();            //行内容
        JSONArray headerName = new JSONArray();         //头部
        JSONArray fieldName = new JSONArray();          //field
        for (int i = 0; i < field.size(); i++) {
            JSONObject webTab = (JSONObject) field.get(i);
            headerName.add(webTab.get("name"));
            fieldName.add(webTab.get("field"));
        }
        JSONObject model = request.get("model");
        Dept receiptDept = deptRepository.findOne(model.getJSONObject("receiptDept").get("id").toString());
        Dept sendDept = deptRepository.findOne(model.getJSONObject("sendDept").get("id").toString());
        List<Object> list = new ArrayList<>();
        List<Object> faCardList = new ArrayList<>();
        importData.forEach((k,v) ->{
            JSONArray excl = (JSONArray) v;
            list.addAll(excl);
        });
        list.remove(0);
        for(int i = 0; i<list.size(); i++){
            JSONArray arrayList = (JSONArray)list.get(i);
            faCardList.add(arrayList.get(2));
        }
        Map<Object, List<Object>> listMap = faCardList.stream().collect(Collectors.groupingBy(lists -> lists));
        listMap.forEach((k,v)->{
            if(v.size() > 1) throw new RuntimeException("此次添加的卡片重复，编码:" + k);
        });
        importData.forEach((k, v) -> {
            //获得value ===Excel内容
            JSONArray excl = (JSONArray) v;
            JSONArray header = (JSONArray) excl.get(0); //首行数据
            for (int i = 0; i < excl.size(); i++) {  //遍历每一行
                if (i == 0) { //跳过首行
                    exclArr.add(headerName);
                    continue;
                }
                JSONArray lineLong = (JSONArray) excl.get(i); //当前行
                //合并2个list为一个map,KEY为首行数据，Value为当前行数据
                Map<String, Object> rst = IntStream.range(0, header.size()).collect(LinkedHashMap::new,
                        (m, key) -> m.put(header.getString(key).replace(";", ""),
                                key >= lineLong.size() ? "" : (lineLong.getString(key) == null ? "" : lineLong.getString(key).trim().replaceAll("[\\s]{2,}", " "))),
                        (m1, m2) -> {
                        });
                FaCard faCard = faCardRepository.findChangeById(rst.get("卡片编码").toString(),sendDept.getId());
                if(faCard == null) throw new RuntimeException("卡片编码:"+rst.get("卡片编码").toString()+"不属于该发货部门或未审核");
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号","");
                map.put("","");
                map.put("卡片编码",faCard);
                map.put("商品",faCard.getProduct());
                map.put("发货部门编码",faCard.getDept().getId());
                map.put("发货部门名称",faCard.getDept().getName());
                map.put("收货部门编码",receiptDept);
                PartyRole responsiblePerson = faCard.getResponsiblePerson();
                map.put("原负责人",responsiblePerson != null ? responsiblePerson.getName() : "");
                map.put("负责人", partyRoleRepository.findByIdOrName(rst.get("负责人").toString(),rst.get("负责人").toString()));
                PartyRole custodian = faCard.getCustodian();
                map.put("原保管人",custodian != null ? custodian.getName() : "");
                map.put("保管人",partyRoleRepository.findByIdOrName(rst.get("保管人").toString(),rst.get("保管人").toString()));
                List valueList = new ArrayList<>(map.values());
                exclArr.add(valueList);
            }
             exclObject.put(k, exclArr);
        });
        return exclObject;
    }
}
